<template>
    <el-dialog :model-value="show" title="分配角色" @close="$emit('hide')">
        <el-select v-model="list" multiple placeholder="请选择" style="width: 240px">
            <el-option v-for="item in roles" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
        <template #footer>
            <el-button @click="emit('hide')">取消</el-button>
            <el-button type="primary" @click="submit">确定</el-button>
        </template>
    </el-dialog>
</template>

<script setup lang="ts">
import { ref, watch } from "vue"
import { getRoleListAPI, getRolesByUserIdAPI, updateUserRolesAPI } from "./api/admin"
import { ElMessage, ElMessageBox } from 'element-plus'

const emit = defineEmits(["hide"]);

const props = defineProps({
    show: {
        type: Boolean,
        default: false,
    },
    id: {
        type: Number,
        default: 0,
    },
});
const list = ref<number[]>([]);
const roles = ref<{ value: number; label: string }[]>([]);

getRoleListAPI().then((res) => {
    if (res.code === 200) {
        roles.value = res.data.map(item => ({
            label: item.name,
            value: item.id
        }))
    }
})

watch(
    () => props.id,
    () => {
        if (props.id === 0) return;
        getRolesByUserIdAPI(props.id).then((res) => {
            if (res.code === 200) {
                list.value = res.data.map((item) => item.id);
            }
        });
    }
);

const submit = () => {
    // 最好也做一下数据验证，正常来说一个用户至少有一个角色，如果产品说可以没有角色就不需要验证
    ElMessageBox.confirm("确定要修改当前用户的角色吗?", "修改用户角色", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
    })
        .then(() => {
            // 发请求
            updateUserRolesAPI(props.id, list.value).then((res) => {
                if (res.code === 200) {
                    // 提示 + 关闭
                    emit("hide");
                    ElMessage.success("修改成功");
                }
            });
        })
        .catch(() => { });
};
</script>

<style scoped>

</style>